/// <summary>
//====================================================================================
///  author          :     Saikumar
///  Created         :     08.11.2013
///  Purpose         :     This page Contains functionality to show Viewing Gallery
///                        Reported Info , post and share
//=======================================================================================
/// </summary>

#region NameSpaces
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Lens.com.Models;
using LenseAPIService.DataAccessLayer;
using log4net;
#endregion
namespace Lens.com.Controllers
{
    public class PhotoGalleryViewController : Controller
    {
        string FilePreupload = ConfigurationManager.AppSettings["FilePreUplodpath"].ToString();      //getting preupload file path       
        string FileUpload = ConfigurationManager.AppSettings["FileUpload"].ToString();               // showing images in galleryview       
        string SaveFilePath = ConfigurationManager.AppSettings["SaveFilePath"].ToString();             //Saving Audio file path
        string LocalDriveFilepath = ConfigurationManager.AppSettings["LocalDriveFilepath"].ToString();

        PhotoGalleryViewModels objPhotoGallery;
        ImagePaging objImageDetails;
        Solutioninfo objSolution;
        DataSet ds;
        DataAccess objDataAcces;
        private static int ReportViewID;
        private static readonly ILog Log = LogManager.GetLogger(typeof(PhotoGalleryViewController));

        /// <summary>
        ///  author          :       Saikumar
        ///  Created         :       08.11.2013
        ///  Purpose         :       This Action method Will render Gallery View initially
        /// </summary>
        /// <param name="ReportID"></param>
        /// <param name="Page"></param>
        /// <returns></returns>
        public ActionResult PhotoGalleryView(int ReportID, string Page)
        {
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
            Log.Info(GlobalConstants.StrStart + methodBase.Name);
            try
            {
                if (Session[GlobalConstants.SessionUserId] == null)
                {
                    return RedirectToAction("Index", "PhotoGallery");
                }
                TempData["ImageModelData"] = null;
                DataAccess objDataAcces = new DataAccess();
                objPhotoGallery = new PhotoGalleryViewModels();

                ReportViewID = ReportID;
                objPhotoGallery = BindViewImage(null, ReportID, Page);
            }
            catch (Exception ex)
            {
                Log.Error(GlobalConstants.StrError + ex);
            }
            finally
            {
                Log.Info(GlobalConstants.StrEnd + methodBase.Name);
            }
            return View(objPhotoGallery);
        }

        /// <summary>
        ///  author          :       Saikumar
        ///  Created         :       08.11.2013
        ///  Purpose         :       This Action method Will  Binding Thumbnail Images        
        /// </summary>
        /// <param name="ImgUrl"></param>
        /// <returns></returns>
        public ActionResult GetImage(string ImgUrl)
        {
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
            Log.Info(GlobalConstants.StrStart + methodBase.Name);
            try
            {
                if (TempData["ImageModelData"] != null)
                {
                    objPhotoGallery = TempData["ImageModelData"] as PhotoGalleryViewModels;
                    TempData["ViewImageUrl"] = ImgUrl;
                    TempData["ImageModelData"] = objPhotoGallery;
                }
                else
                {
                    objPhotoGallery = BindViewImage(ImgUrl, 1, null);
                }
            }
            catch (Exception ex)
            {
                Log.Error(GlobalConstants.StrError + ex);
            }
            finally
            {
                Log.Info(GlobalConstants.StrEnd + methodBase.Name);
            }

            return View("PhotoGalleryView", objPhotoGallery);
        }

        /// <summary>
        ///  author          :       Saikumar
        ///  Created         :       08.11.2013
        ///  Purpose         :       This Action method Will  Binding Reported Info          
        /// </summary>
        /// <param name="ImgUrl"></param>
        /// <param name="ReportID"></param>
        /// <param name="Flag"></param>
        /// <param name="objListDynamic"></param>
        /// <returns></returns>
        private PhotoGalleryViewModels BindViewImage(string ImgUrl, int ReportID, string Flag)
        {
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
            Log.Info(GlobalConstants.StrError + methodBase.Name);
            try
            {
                objDataAcces = new DataAccess();
                if (TempData["ViewImageUrl"] == null)
                    TempData["ViewImageUrl"] = GlobalConstants.DefaultImageUrl;
                if (TempData["ImageModelData"] == null)
                {
                    objPhotoGallery = new PhotoGalleryViewModels();
                    string mobile = string.Empty;
                    string EmailId = string.Empty;
                    string StateName = string.Empty;
                    string UserName = string.Empty;
                    DataTable dtReportdet = objDataAcces.GetGalleryDetailsView(Convert.ToInt32(ReportID), Convert.ToInt32(Session[GlobalConstants.SessionUserId]), null, 0, 0, 0, Flag,out mobile, out EmailId, out StateName,out UserName);
                    if (dtReportdet.Rows.Count > 0)
                    {
                        ReportViewID = Convert.ToInt32(dtReportdet.Rows[0]["ReportId"].ToString());
                        objPhotoGallery.ProblemId = dtReportdet.Rows[0]["ReportId"].ToString();                       
                        objPhotoGallery.ReportedDate = Convert.ToDateTime(dtReportdet.Rows[0]["PostedDate"]); 
                        objPhotoGallery.Observation = dtReportdet.Rows[0]["ReportComments"].ToString();
                        //objPhotoGallery.ReportTitle = dtReportdet.Rows[0]["ReportTitle"].ToString();
                        objPhotoGallery.MobileNo = mobile;
                        objPhotoGallery.StateName = StateName;
                        objPhotoGallery.EmailId = EmailId;
                        objPhotoGallery.Name = UserName;
                        if (!string.IsNullOrEmpty(Convert.ToString(dtReportdet.Rows[0]["ReportAudioPath"])))
                        {
                            bool FileStatus = CheckAudioFile(dtReportdet.Rows[0]["ReportAudioPath"].ToString());
                            if (FileStatus)
                                objPhotoGallery.AudioPath = FileUpload + dtReportdet.Rows[0]["ReportAudioPath"].ToString();
                        }
                        else
                        {
                            objPhotoGallery.AudioPath = null;
                        }
                       // ReportViewID = ReportID;
                    }
                    else
                    {
                        dtReportdet = objDataAcces.GetGalleryDetailsView(Convert.ToInt32(ReportID), Convert.ToInt32(Session[GlobalConstants.SessionUserId]), null, 0, 0, 0, null, out mobile, out EmailId, out StateName, out UserName);
                        if (dtReportdet.Rows.Count > 0)
                        {
                            objPhotoGallery.ProblemId = dtReportdet.Rows[0]["ReportId"].ToString();
                            objPhotoGallery.ReportedDate = Convert.ToDateTime(dtReportdet.Rows[0]["PostedDate"]);
                            objPhotoGallery.Observation = dtReportdet.Rows[0]["ReportComments"].ToString();
                            //objPhotoGallery.ReportTitle = dtReportdet.Rows[0]["ReportTitle"].ToString();
                            objPhotoGallery.MobileNo = mobile;
                            objPhotoGallery.StateName = StateName;
                            objPhotoGallery.EmailId = EmailId;
                            objPhotoGallery.Name = UserName;
                            if (!string.IsNullOrEmpty(Convert.ToString(dtReportdet.Rows[0]["ReportAudioPath"])))
                            {
                                bool FileStatus = CheckAudioFile(dtReportdet.Rows[0]["ReportAudioPath"].ToString());
                                if (FileStatus)
                                    objPhotoGallery.AudioPath = FileUpload + dtReportdet.Rows[0]["ReportAudioPath"].ToString();
                            }
                            else
                            {
                                objPhotoGallery.AudioPath = null;
                            }
                        }
                    }
                    objPhotoGallery.ListDynamic = BindDynamicControls();
                    objPhotoGallery.GroupList = BindGroups();
                   objPhotoGallery.SolutionList= BindSolutions(); 
                    BindImageIcons();
                    
                    TempData["ImageModelData"] = objPhotoGallery;
                    return objPhotoGallery;
                }
                objPhotoGallery = TempData["ImageModelData"] as PhotoGalleryViewModels;
                return objPhotoGallery;
            }
            catch (Exception ex)
            {
                Log.Error(GlobalConstants.StrError + ex);
                return null;
            }
            finally
            {
                Log.Info(GlobalConstants.StrEnd + methodBase.Name);
            }
        }

        /// <summary>
        ///  author          :       Saikumar
        ///  Created         :       08.11.2013
        ///  Purpose         :       This Action method Will  Getting Paging Report Details     
        /// </summary>
        /// <param name="id"></param>
        /// <param name="Flag"></param>
        /// <returns></returns>
        public ActionResult GetPagingImage(int id, string Flag)
        {
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
            Log.Info(GlobalConstants.StrStart + methodBase.Name);
            try
            {
                return RedirectToAction("PhotoGalleryView", "PhotoGalleryView", new { ReportID = id, Page = Flag });
            }
            catch (Exception ex)
            {
                Log.Error(GlobalConstants.StrError + ex);
                return null;
            }
            finally
            {
                Log.Info(GlobalConstants.StrEnd + methodBase.Name);
            }
        }

        /// <summary>
        ///  author         :   Saikumar
        ///  Created        :   08.11.2013
        ///  Purpose        :   This Action method Will  Uploading Audio ,posting solution and sharing solution         
        /// </summary>
        /// <param name="AudioFileUpload"></param>
        /// <param name="frmcoll"></param>
        /// <param name="reporid"></param>
        /// <param name="Command"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Upload(HttpPostedFileBase AudioFileUpload, FormCollection frmcoll, string reporid, string Command)
        {
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
            Log.Info(GlobalConstants.StrStart + methodBase.Name);
            try
            {
                objDataAcces = new DataAccess();
                int ProblemID = Convert.ToInt32(frmcoll["HiddenReportID"]);
                if (AudioFileUpload != null)
                    if (Request.Files.Count == 1)
                    {
                        DeletePreUpoadFiles();
                        if (AudioFileUpload.ContentLength > 0)
                        {
                            var fileName = Path.GetFileName(AudioFileUpload.FileName);
                            var path = Path.Combine(Server.MapPath(FilePreupload) + Session[GlobalConstants.SessionUserId] + "/", fileName);
                            if (!Directory.Exists(Server.MapPath(FilePreupload).ToString() + Session[GlobalConstants.SessionUserId]))
                            {
                                Directory.CreateDirectory(Server.MapPath(FilePreupload).ToString() + Session[GlobalConstants.SessionUserId]);
                                AudioFileUpload.SaveAs(path);
                            }
                            else
                            {
                                AudioFileUpload.SaveAs(path);
                            }
                            TempData["Audio"] = GlobalConstants.AudioSuccess;
                        }
                    }
                if (Command == GlobalConstants.Post)
                {
                    string SolutionInfo = frmcoll["AddSolution"].ToString();
                    string SolutionFileName = null;
                    DirectoryInfo sourceinfo = new DirectoryInfo(Server.MapPath(FilePreupload + Session[GlobalConstants.SessionUserId].ToString() + "/"));
                    DirectoryInfo target = new DirectoryInfo(SaveFilePath + Convert.ToInt32(Session[GlobalConstants.SessionUserId]));
                    FileInfo[] files = null;
                    try
                    {
                        if (sourceinfo.Exists)
                        {
                            files = sourceinfo.GetFiles();
                        }
                        if (files != null)
                            foreach (FileInfo file in files)
                            {
                                if (!System.IO.File.Exists(target.ToString() + "/" + file.Name))
                                {
                                    string datetimefileName = DateTime.Now.ToString(GlobalConstants.StrDateTimeFormat);
                                    if (!Directory.Exists(SaveFilePath + Convert.ToInt32(Session[GlobalConstants.SessionUserId])))
                                    {
                                        Directory.CreateDirectory(SaveFilePath + Convert.ToInt32(Session[GlobalConstants.SessionUserId]));
                                    }
                                    file.MoveTo(target + ("/" + datetimefileName) + file.Extension);
                                    SolutionFileName = (Session[GlobalConstants.SessionUserId].ToString() + "/" + datetimefileName) + file.Extension;
                                }
                            }
                    }
                    catch (Exception ex)
                    {

                    }
                    if (!string.IsNullOrEmpty(SolutionFileName) || !string.IsNullOrEmpty(SolutionInfo))
                    {
                        int Status = objDataAcces.InsertReportSolutionDetails(ProblemID, SolutionFileName, null, SolutionInfo, Convert.ToInt32(Session[GlobalConstants.SessionUserId]));
                        if (Status > 0)
                            TempData[GlobalConstants.Posted] = GlobalConstants.strPostSuccessmsg;
                        else
                            TempData[GlobalConstants.Posted] = GlobalConstants.strPostFailedmsg;
                    }
                    else
                    {
                        TempData[GlobalConstants.Posted] = GlobalConstants.strPostValidatesmsg;
                    }
                    TempData["ImageModelData"] = null;
                }
                if (Command == GlobalConstants.Share)
                {
                    StringBuilder strBldrgrps = new StringBuilder();
                    string grpID = string.Empty;
                    for (int i = 0; i < frmcoll.Count; i++)
                    {
                        if (!string.IsNullOrEmpty(frmcoll[i.ToString()]))
                        {
                            if (frmcoll[i.ToString()].Contains(GlobalConstants.strStatus))
                            {
                                strBldrgrps.Append(i);
                                strBldrgrps.Append(',');
                            }
                        }
                    }
                    if (strBldrgrps.Length > 0)
                        grpID = strBldrgrps.ToString().Substring(0, strBldrgrps.ToString().Length - 1);
                    if (!string.IsNullOrEmpty(grpID) || !string.IsNullOrEmpty(frmcoll[GlobalConstants.StrtxtMobileNo]))
                    {
                        objDataAcces.InsertReportAssignedDetails(ProblemID, grpID, null, frmcoll[GlobalConstants.StrtxtMobileNo], Convert.ToInt32(Session[GlobalConstants.SessionUserId]));
                        TempData[GlobalConstants.Shared] = GlobalConstants.strShareMsg;
                    }
                }
                string Flag = null;
                return RedirectToAction("PhotoGalleryView", new { ReportID = ProblemID, Page = Flag });
            }
            catch (Exception ex)
            {
                Log.Error(GlobalConstants.StrError + ex);
                return null;
            }
            finally
            {
                Log.Info(GlobalConstants.StrEnd + methodBase.Name);
            }
        }

        /// <summary>
        ///  author          :  Saikumar
        ///  Created         :  08.11.2013
        ///  Purpose         :  This  method Will Deleting PreUpload Audiofiles from Preupload folder before creating.        
        /// </summary>
        private void DeletePreUpoadFiles()
        {
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
            Log.Info(GlobalConstants.StrStart + methodBase.Name);
            try
            {
                if (Directory.Exists(Server.MapPath(FilePreupload + Session[GlobalConstants.SessionUserId].ToString())))
                {
                    string[] fileNames = Directory.GetFiles(Server.MapPath(FilePreupload).ToString() + Session[GlobalConstants.SessionUserId].ToString());
                    foreach (string fileName in fileNames)
                        System.IO.File.Delete(fileName);
                    //Directory.Delete(Server.MapPath(FilePreupload).ToString() + Session["UserID"].ToString());
                }
            }
            catch (Exception ex)
            {
                Log.Error(GlobalConstants.StrError + ex);
            }
            finally
            {
                Log.Info(GlobalConstants.StrEnd + methodBase.Name);
            }
        }

        /// <summary>
        ///  author          :       Saikumar
        ///  Created         :       08.11.2013
        ///  Purpose         :       This  method Will  Check Audio file in phisycal folder exist or not exist         
        /// </summary>
        /// <param name="DbAduioFilePath"></param>
        /// <returns></returns>
        private bool CheckAudioFile(string DbAduioFilePath)
        {
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
            Log.Info(GlobalConstants.StrStart + methodBase.Name);
            try
            {
                if (System.IO.File.Exists(LocalDriveFilepath + DbAduioFilePath))
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                Log.Error(GlobalConstants.StrError + ex);
            }
            finally
            {
                Log.Info(GlobalConstants.StrEnd + methodBase.Name);
            }
            return false;
        }

        /// <summary>
        ///  author          :       Saikumar
        ///  Created         :       08.11.2013
        ///  Purpose         :       This  method Will  binding usergroups
        /// </summary>
        private List<Groups> BindGroups()
        {
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
            Log.Info(GlobalConstants.StrError + methodBase.Name);
            try
            {

                DataSet dsGroups = objDataAcces.GetGroups();
                List<Groups> objGroup = new List<Groups>();
                if (dsGroups.Tables[0].Rows.Count > 0)
                {
                    var Group = dsGroups.Tables[0].AsEnumerable().Select(d => new
                    {
                        GroupId = d.Field<int>("GroupId"),
                        GroupName = d.Field<string>("GroupName")
                    });
                    foreach (var item in Group)
                    {
                        Groups objclsGroup = new Groups();
                        objclsGroup.GroupId = item.GroupId;
                        objclsGroup.GroupName = item.GroupName;
                        objGroup.Add(objclsGroup);
                    }
                    objPhotoGallery.GroupList = objGroup;
                }
                return objGroup;
            }
            catch (Exception ex)
            {
                Log.Error(GlobalConstants.StrError + ex);
                return null;
            }
            finally
            {
                Log.Info(GlobalConstants.StrEnd + methodBase.Name);
            }

        }
        /// <summary>
        ///  author          :       Saikumar
        ///  Created         :       08.11.2013
        ///  Purpose         :       This  method Will  binding ImageThumnails
        /// <param name="ReportID"></param>
        /// <returns></returns>
        private PhotoGalleryViewModels BindImageIcons()
        {

            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
            Log.Info(GlobalConstants.StrError + methodBase.Name);
            try
            {
                DataTable dtImageDets = objDataAcces.GetGalleryDetailsImages(Convert.ToInt32(ReportViewID));
                if (dtImageDets.Rows.Count > 0)
                {
                    for (int i = 0; i < dtImageDets.Rows.Count; i++)
                    {
                        if (i == 0)
                        {
                            TempData["ViewImageUrl"] = Path.Combine(FileUpload + dtImageDets.Rows[i]["ImagePath"].ToString());
                        }
                        objImageDetails = new ImagePaging();
                        objImageDetails.PageNumber = i + 1;
                        objImageDetails.ImageUrl = Path.Combine(FileUpload + dtImageDets.Rows[i]["ImagePath"].ToString());
                        objPhotoGallery.ImageList.Add(objImageDetails);
                    }
                }
                return objPhotoGallery;
            }
            catch (Exception ex)
            {
                Log.Error(GlobalConstants.StrError + ex);
                return null;
            }
            finally
            {
                Log.Info(GlobalConstants.StrEnd + methodBase.Name);
            }
        }

        /// <summary>
        ///  author          :       Saikumar
        ///  Created         :       08.11.2013
        ///  Purpose         :       This  method Will  binding Reported Solutions
        /// <param name="ReportID"></param>
        /// <returns></returns>
        private List<Solutioninfo> BindSolutions()
        {
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
            Log.Info(GlobalConstants.StrError + methodBase.Name);
            try
            {
                DataTable dtReponses = objDataAcces.GetReportSolutions(ReportViewID);
                List<Solutioninfo> objSolutionList = new List<Solutioninfo>();
                if (dtReponses.Rows.Count > 0)
                {
                    for (int i = 0; i < dtReponses.Rows.Count; i++)
                    {
                        objSolution = new Solutioninfo();
                        objSolution.Solution = dtReponses.Rows[i]["Solution"].ToString();
                        objSolution.reportedby = dtReponses.Rows[i]["UserName"].ToString();
                        objSolution.SolutionDate = Convert.ToDateTime(dtReponses.Rows[i]["CreatedDate"]);
                        objSolutionList.Add(objSolution);
                    }
                }
                return objSolutionList;
            }
            catch (Exception ex)
            {
                Log.Error(GlobalConstants.StrError + ex);
                return null;
            }
            finally
            {
                Log.Info(GlobalConstants.StrEnd + methodBase.Name);
            }
        }

        /// <summary>
        ///  author          :  Saikumar
        ///  Created         :  18.12.2013
        ///  Purpose         :  This  method Will  Dynamically Binding Controls 
        ///                     Supporting inforamtion        
        /// <returns></returns>
        private List<DynamicClass> BindDynamicControls()
        {
            System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
            System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
            Log.Info(GlobalConstants.StrError + methodBase.Name);
            try
            {
                DataTable dtDynamicControls = objDataAcces.GetDynamicLoadGalleryViewControls(ReportViewID);
                List<DynamicClass> lstLoadControl = new List<DynamicClass>();
                var DynamicControls = dtDynamicControls.AsEnumerable().Select(d => new
                {
                    AttributeId = d.Field<int>("AttributeId"),
                    AttributeName = d.Field<string>("AttributeName"),
                    AttributeType = d.Field<string>("AttributeType"),
                    AttributeValueLookup = d.Field<string>("AttributeValueLookup"),
                    Description = d.Field<string>("Description"),
                    FunctionID = d.Field<int>("FunctionID"),
                    AttributeText = d.Field<string>("AttributeText")

                });
                foreach (var item in DynamicControls)
                {
                    DynamicClass objDynimiccls = new DynamicClass();
                    objDynimiccls.AttributeId = item.AttributeId;
                    objDynimiccls.AttributeName = item.AttributeName;
                    objDynimiccls.AttributeType = item.AttributeType;
                    objDynimiccls.AttributeValueLookup = item.AttributeValueLookup;
                    objDynimiccls.Description = item.Description;
                    objDynimiccls.FunctionID = item.FunctionID;
                    objDynimiccls.AttributeText = item.AttributeText;
                    lstLoadControl.Add(objDynimiccls);
                }
                return lstLoadControl;
            }
            catch (Exception ex)
            {
                Log.Error(GlobalConstants.StrError + ex);
                return null;
            }
            finally
            {
                Log.Info(GlobalConstants.StrEnd + methodBase.Name);
            }
        }

    }
}
